package f3a.learningservice;

import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;

import android.os.Bundle;
import android.os.Handler;
import android.app.Activity;
import android.content.Intent;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.TextView;

public class MainActivity extends Activity {
	
	private TimeManager clock;
	private Timer refresh;
	private TimerTask task;
	private Handler handle = new Handler();
	private TextView text;
	private static ArrayList<Activity> activities=new ArrayList<Activity>();
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		activities.add(this);
		
		
		text = (TextView) findViewById(R.id.clock);
		
		clock = new TimeManager((long) (5.3*60000),"seconds","down","HH:MM:SS:mmm");
		
		
		initTimer();	
			
		
	}
	
	private void initTimer(){
		refresh = new Timer();
		task = new TimerTask(){
			public void run(){
				handle.post(new Runnable(){
					public void run(){
						escreveRelogio();
						Log.d("Debug","Timer");
					}
				});
			}
		};
		refresh.schedule(task, 1000, 1000);
	}
	
	private void stopTimer(){
		task.cancel();
		task = null;
		refresh.cancel();
		refresh = null;
		handle = null;
	}
	
	private void escreveRelogio(){
		text.setText(clock.toString());
	}
	
	public void startOnClick(View start){
		
		clock.start();
		
	}
	
	public void pauseOnClick(View pause){
		
		clock.pause();
		
	}
	
	public void startServiceOnClick(View startService){
		
		startService(new Intent(this, ClockService.class));
		
	}
	
	public void pauseServiceOnClick(View pauseService){
		
		stopService(new Intent(this, ClockService.class));
		
	}
	
	@Override
	public void onStop(){
		super.onStop();
		Log.d("Debug", "onStop");
		stopTimer();
	}
	
	@Override
	public void onRestart(){
		super.onRestart();
		Log.d("Debug", "onRestart");
		initTimer();
	}
	
	@Override
	public void onDestroy(){
		super.onDestroy();
		Log.d("Debug", "Destroy");
		activities.remove(this);
		
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

}
